package com.cf.web.servlet;

import com.cf.dao.ActiveDao;
import com.cf.dao.entity.Active;
import com.cf.dao.entity.ActiveResponse;
import com.cf.dao.impl.ActiveDaoImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
@WebServlet(name = "ActiveServlet", value = "/active/*")
public class ActiveServlet extends HttpServlet {
    private ActiveDao activeDao = new ActiveDaoImpl();
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String pathInfo = req.getPathInfo();
    if (pathInfo != null) {
        switch (pathInfo) {
            case "/all":
                try {
                    findactive(req, res);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                break;
            default:
                res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid endpoint");
        }
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing endpoint");
    }
}
    //获取所有活动
    private void findactive(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String imgurls = null;
        // 获取活动信息
        Active active = activeDao.active();
        // 获取图片地址字符串
        imgurls = active.getImg();
        // 确保 imgurls 不为 null 或空
        List<String> imageList = null;
        if (imgurls != null && !imgurls.trim().isEmpty()) {
            // 拆分图片地址并转换为 List
            imageList = Arrays.asList(imgurls.split(","));
        }
        // 创建 ActiveResponse 对象，将 active 和 imageList 封装在一起
        ActiveResponse activeResponse = new ActiveResponse(active, imageList);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 将 ActiveResponse 对象转换为 JSON 字符串
        String json = objectMapper.writeValueAsString(activeResponse);
        // 设置响应内容类型为 JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        // 输出 JSON 响应
        resp.getWriter().write(json);
    }
}
